from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django_filters.rest_framework import DjangoFilterBackend

from rest_framework import viewsets
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

from XApiTestServer.models import UserInfo, UserToken
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import UserSerializer

from XApiTestServer.utils.response import *
from XApiTestServer.utils.auth import *

import logging


logger = logging.getLogger('XApiTestServer')


@api_view(('POST',))
def login(request):
    """
    Login the system.
    :param request:
    :return:
    """
    try:
        kwargs = json.loads(request.body.decode('utf-8'))
        account = kwargs.pop('username')
        password = kwargs.pop('password')
        type = kwargs.pop('type', 'Normal')
        logger.info("Login Info - Account: {}, Password: {}, Type: {}".format(account, password, type))
    except KeyError:
        return Response(KEY_MISS)

    if type == 'Normal':
        return login_normal(account, password)
    else:
        return Response(LOGIN_FAILED_LDAP)
    ''' 
        # Login with ldap
        user = account + "@xxxx.com"
    
        if login_ldap(account, password):
            validate_ldap_user(account, password)
        else:
            return Response(LOGIN_FAILED)
    '''

@api_view(('GET',))
def logout(request):
    """
    注销登录
    :param request:
    :return:
    """
    kwargs = json.loads(request.header.decode('utf-8'))
    try:
        kwargs = json.loads(request.header.decode('utf-8'))
        token = kwargs.pop('token')
    except KeyError:
        return Response(SYSTEM_ERROR)
    return Response(LOGIN_SUCCESS)

def get_password(request):
    """
    修改密碼时先获取旧密码校验
    :param request:
    :return:
    """
    kwargs = json.loads(request.body.decode('utf-8'))
    account = kwargs.pop('username')
    password = UserInfo.objects.get(username=account).password
    print(password)
    logger.info("User {} get password to modify".format(account))

    response_body = SUCCESS_INFO
    response_body['data'] = password
    return JsonResponse(response_body)

def update_password(request):
    """
    修改密碼
    :param request:
    :return:
    """
    kwargs = json.loads(request.body.decode('utf-8'))
    account = kwargs.pop('username')
    password = kwargs.pop('password')
    UserInfo.objects.filter(username=account).update(password=password)
    logger.info("User {} modify password, new password is {}".format(account,password))

    response_body = SUCCESS_UPDATE
    response_body['msg'] = '修改密码成功！'
    return JsonResponse(response_body)


class UserViewSet(viewsets.ModelViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('username',)
    filterset_fields = ('status',)
    ordering_fields = ('update_time', )

    def _userinfo_validator(self, request, *args, **kwargs):
        if not request.data['username']:
            msg = '用户名称(username)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if not request.data['password']:
            msg = '用户密码(password)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if not request.data['email']:
            msg = '搜索模块(belong_module)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if request.data['password'] != request.data['repassword']:
            msg = '两次输入密码必须相等'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

    def _userinfo_unique_validator(self, request, *args, **kwargs):
        username = request.data['username']
        email = request.data['email']

        user_info = UserInfo.objects

        if user_info.filter(username__exact=username).filter(status=1).count() > 0:
            msg = '{username} 已被其他用户注册'.format(username=username)
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)
        if user_info.filter(email__exact=email).filter(status=1).count() > 0:
            msg = '邮箱:{email},已被其他用户注册'.format(email=email)


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data

        return Response(response_body)

    def create(self, request, *args, **kwargs):
        self._userinfo_validator(request, *args, **kwargs)
        self._userinfo_unique_validator(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        self._userinfo_validator(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid(raise_exception=True):
            self.perform_update(serializer)

            response_body = SUCCESS_UPDATE
            response_body['data'] = serializer.data
            return Response(response_body)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)
